package com.puman.watchtrade.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.puman.watchtrade.MainActivity;
import com.puman.watchtrade.R;
import com.puman.watchtrade.adapter.LeftCateGoryAdapter;
import com.puman.watchtrade.fragment.home.HomeFragment;
import com.puman.watchtrade.fragment.info.InfoFregment;
import com.puman.watchtrade.fragment.personal.PersonalCenterFragment;
import com.puman.watchtrade.fragment.sell.SellFragment;
import com.puman.watchtrade.fragment.sell.util.UniversalImageLoadTool;
import com.puman.watchtrade.fragment.set.AboutFragment;
import com.puman.watchtrade.fragment.set.LoginFragment;
import com.puman.watchtrade.fragment.set.httpHandler.SettingHttpHandler;
import com.puman.watchtrade.model.ItemCategoryModel;
import com.puman.watchtrade.util.DataResult;
import com.puman.watchtrade.util.Gjfun;
import com.puman.watchtrade.util.GlobalData;
import com.puman.watchtrade.util.LoadingProgressDialog;

/**
 * 
 * @author curry
 * 
 */
public class LeftCategoryFragment extends Fragment implements OnClickListener {
	private View mView;
	private Context mContext;
	private ListView listview_right_category;
	private LeftCateGoryAdapter mAdapter;
	private String[] category_name;
	private Integer[] category_img;
	private List<ItemCategoryModel> mLists;
	private Context myContext;
	private RelativeLayout loginLayout;//
	private static TextView loginInfo;
	public static TextView userName;
	public static TextView loginBtnInfo;
	private static final String APP_CACAHE_DIRNAME = "/webcache";
	// private static TextView userPosi;
	// private static TextView userPosiNum;
	/*
	 * callback ��־
	 */
	public static final int EXIT_SUC = 0x01;
	public static final int EXIT_FAIL = 0x02;
	public static final int TIME_OUT = 0x03;
	public static final int LOGINOUT_SUC = 0x04;
	public static final int LOGINOUT_FAIL = 0x05;
	public static final int CLEAN = 0x06;

	/*
	 * init var
	 */
	private DataResult httpResult = new DataResult();
	private SharedPreferences sharedPreferences; // 私有数据
	private Editor editor;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		relativeLayout = (RelativeLayout) inflater.inflate(R.layout.main,
				container, false).findViewById(R.id.main_non_bottom);

		myContext = this.getActivity();
		if (null == mView) {
			mView = inflater.inflate(R.layout.left_category, container, false);
			initView();
			initValidata();
			bindData();
			initListener();
		}
		if (GlobalData.userInfo != null) {
			LeftCategoryFragment.setLoginValue();
		}
		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		super.onActivityCreated(savedInstanceState);
		initView();
		initValidata();
		bindData();
		initListener();
	}

	private RelativeLayout relativeLayout;

	/**
	 * 初始化
	 */
	private void initView() {
		sharedPreferences = MainActivity.getInstant().getSharedPreferences(
				"watchtrade", Context.MODE_PRIVATE);
		editor = sharedPreferences.edit();// 获取编辑器
		
		
		
		listview_right_category = (ListView) mView
				.findViewById(R.id.listview_left_category);

		mView.findViewById(R.id.login_layout).setOnClickListener(this);

		loginInfo = (TextView) mView.findViewById(R.id.login_info);

		userName = (TextView) mView.findViewById(R.id.login_info_user);
		loginBtnInfo = (TextView) mView
				.findViewById(R.id.login_layout_btn_info);

	}

	public static void setLoginValue() {
		if (GlobalData.userInfo != null) {
			loginInfo.setText("");
		}

	}

	private void exitLogin() {
		if (GlobalData.userInfo == null) {
			return;
		}
		loginInfo.setText("");
		exit();
	}

	private void exit() {
	}

	Callback callback = new Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			switch (msg.what) {
			case EXIT_SUC:
				Toast.makeText(MainActivity.getInstant(), httpResult.msg,
						Toast.LENGTH_SHORT).show();
				break;
			case EXIT_FAIL:
				Toast.makeText(MainActivity.getInstant(), httpResult.msg,
						Toast.LENGTH_SHORT).show();
				break;
			case TIME_OUT:
				Toast.makeText(MainActivity.getInstant(), "", Toast.LENGTH_LONG)
						.show();
				break;
			case LOGINOUT_SUC:
				Gjfun.stopProgressDialog(mProgress);
				Toast.makeText(MainActivity.getInstant(), "" + dataResult.msg,
						Toast.LENGTH_SHORT).show();
				GlobalData.userInfo = null;
				userName.setText("未登录");
				loginBtnInfo.setText("登录 ");
				editor.putString("mobile","");
				editor.putString("password","");
				editor.commit();
				break;
			case LOGINOUT_FAIL:
				Gjfun.stopProgressDialog(mProgress);
				Toast.makeText(MainActivity.getInstant(), "" + dataResult.msg,
						Toast.LENGTH_SHORT).show();
				break;
			case CLEAN:
				Toast.makeText(MainActivity.getInstant(), "缓存已经抖空空....",
						Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
			return false;
		}
	};
	Handler handler = new Handler(callback);

	/**
	 * 初始化item
	 */
	private void initValidata() {
		mContext = mView.getContext();
		category_name = mContext.getResources().getStringArray(
				R.array.category_name);
		// category_title = mContext.getResources().getStringArray(
		// R.array.category_title);//�����Ŀ Ӣ��
		category_img = new Integer[] { R.drawable.left_1, R.drawable.left_2,
				R.drawable.left_3, R.drawable.left_4, R.drawable.left_5,
				R.drawable.left_5 };// ��ӦͼƬ

		mLists = new ArrayList<ItemCategoryModel>();
		for (int i = 0; i < category_img.length; i++) {
			mLists.add(new ItemCategoryModel(category_img[i], category_name[i]));
		}
		mAdapter = new LeftCateGoryAdapter(mContext, mLists);
	}

	/**
	 */
	private void bindData() {
		listview_right_category.setAdapter(mAdapter);
	}

	/**
	 */
	private void initListener() {
		listview_right_category
				.setOnItemClickListener(new MyOnItemClickListener());
	}

	/**
	 * 
	 * @author curry
	 * 
	 */
	class MyOnItemClickListener implements OnItemClickListener {

		public void onItemClick(AdapterView<?> l, View v, int position, long id) {
			Fragment newContent = null;
			// FragmentTransaction transaction = MainActivity.fragmentManager
			// .beginTransaction();
			MainActivity.getSlidingmunu().toggle();
			Fragment fragment = null;
			MainActivity.fragmentManager.popBackStack(null,
					FragmentManager.POP_BACK_STACK_INCLUSIVE);
			boolean jump = false;
			switch (position) {
			case 0:
				fragment = new HomeFragment();
				break;
			case 1:
				fragment = new SellFragment(false);
				break;
			case 2:
				fragment = new InfoFregment();
				break;
			case 3:
				// if (GlobalData.userInfo == null) {
				// LoginFragment loginFragment = new LoginFragment();
				// transaction.replace(R.id.main_non_bottom, loginFragment);
				// transaction.addToBackStack(null);
				// transaction.commit();
				// break;
				// }
				fragment = new PersonalCenterFragment();
				break;
			case 4:
				// fragment = new AboutFragment();
				UniversalImageLoadTool.clear();
				com.puman.watchtrade.fragment.home.imageLoader.util.UniversalImageLoadTool.clear();
				Animation anim = AnimationUtils.loadAnimation(
						MainActivity.getInstant(), R.anim.myanim);
				RelativeLayout relativeLayout = (RelativeLayout) MainActivity
						.getInstant().findViewById(R.id.main_non_bottom);
				relativeLayout.startAnimation(anim);
				
				String cacheDirPath = MainActivity.getInstant().getFilesDir()
						.getAbsolutePath()
						+ APP_CACAHE_DIRNAME;
				Log.i("curry", "cacheDirPath:"+cacheDirPath);
				File file = new File(cacheDirPath);
				clearCacheFolder(file, 30);
				
				// 震动  
				Vibrator vibrator = (Vibrator) MainActivity.getInstant().getSystemService(MainActivity.getInstant().VIBRATOR_SERVICE);      
				vibrator.vibrate(1000); 
				Message msg = new Message();
				msg.what = CLEAN;
				handler.sendMessageDelayed(msg, 1500);
				jump = true;
				break;
			case 5:
				fragment = new AboutFragment("3");
				break;
			}
			if (!jump) {
				MainActivity.getInstant().getSupportFragmentManager()
						.beginTransaction()
						.replace(R.id.main_non_bottom, fragment).commit();
				if (newContent != null) {
					switchFragment(newContent);
				}
			}

		}
	}
	private int clearCacheFolder(File dir, long numDays) {        
	    int deletedFiles = 0;       
	    if (dir!= null && dir.isDirectory()) {           
	        try {              
	            for (File child:dir.listFiles()) {  
	                if (child.isDirectory()) {            
	                    deletedFiles += clearCacheFolder(child, numDays);        
	                }  
	                if (child.lastModified() < numDays) {   
	                    if (child.delete()) {                 
	                        deletedFiles++;         
	                    }  
	                }  
	            }           
	        } catch(Exception e) {     
	            e.printStackTrace();  
	        }   
	    }     
	    return deletedFiles;   
	}  
	private void switchFragment(Fragment fragment) {
		if (getActivity() == null) {
			return;
		}
		if (getActivity() instanceof MainActivity) {
			MainActivity fca = (MainActivity) getActivity();
			fca.switchContent(fragment);
		}
	}

	@Override
	public void onClick(View v) {
		MainActivity.fragmentManager.popBackStack(null,
				FragmentManager.POP_BACK_STACK_INCLUSIVE);
		MainActivity.getSlidingmunu().toggle();
		FragmentTransaction transaction = MainActivity.fragmentManager
				.beginTransaction();
		switch (v.getId()) {
		case R.id.login_layout:
			if (GlobalData.userInfo == null) {
				LoginFragment loginFragment = new LoginFragment();
				transaction.replace(R.id.main_non_bottom, loginFragment);
				transaction.addToBackStack(null);
				transaction.commit();
			} else {
				loginOut();
				// GlobalData.userInfo = null;
				// userName.setText("未登录");
				// loginBtnInfo.setText("登录 ");
			}
			break;
		default:
			break;
		}

	}

	private LoadingProgressDialog mProgress = null;

	private void loginOut() {
		mProgress = Gjfun.startProgressDialog(mProgress, getActivity());
		((MainActivity) getActivity()).cachedThreadPoolMinPriority
				.execute(loginOutRunnable);
	}

	private SettingHttpHandler settingHttpHandler = new SettingHttpHandler();
	private DataResult dataResult = new DataResult();
	/*
	 * 获取 商品详情
	 */
	Runnable loginOutRunnable = new Runnable() {
		@Override
		public void run() {
			int what = LOGINOUT_FAIL;
			dataResult = settingHttpHandler.loginOut();
			if (dataResult.flag) {
				what = LOGINOUT_SUC;
			}
			sendMessage(what);
		}
	};

	private void sendMessage(int what) {
		Message msg = new Message();
		msg.what = what;
		handler.sendMessage(msg);
	}
}
